package com.suse.lhw.hms.authserver.config;

import com.suse.lhw.hms.authserver.domin.UPermission;
import com.suse.lhw.hms.authserver.domin.UUser;
import com.suse.lhw.hms.authserver.service.UUserService;
import com.suse.lhw.hms.authserver.service.UPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: health_manage_system
 * @Package: com.suse.lhw.hms.authserver.config
 * @ClassName: UserDetailsServiceImpl
 * @Description: 负责从数据库拉取用户信息和权限交给Security授权
 * @Author: 李鸿炜
 * @CreateDate: 2020/3/28 17:57
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/3/28 17:57
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    public void setuUserService(UUserService uUserService) {
        this.uUserService = uUserService;
    }

    private UUserService uUserService;
    @Autowired
    private UPermissionService uPermissionService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("啊啊发斯蒂芬the string ocured is : " + s);
        UUser uUser = uUserService.loginByPrimarryKeyAndPsd(s);
        if (uUser == null) {
            System.out.println("the user is null");
            throw new UsernameNotFoundException(s + "is not exit");
        }

        System.out.println(uUser.toString());
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
        if (uUser != null) {
            System.out.println("uUser != null ,so let s go to for!");
            List<UPermission> uPermissionList = uPermissionService.getUsersPermissions(s);
            for (UPermission permission : uPermissionList) {
                System.out.println("\n" + permission.getChineseDescription());
            }
            for (UPermission uPermission : uPermissionList) {
                GrantedAuthority g = new SimpleGrantedAuthority(uPermission.getName());
                grantedAuthorityList.add(g);
            }
        }
        System.out.println("看看这里能否被执行");
        return new User(uUser.getNickname(), uUser.getPassword(), grantedAuthorityList);
    }
}
